package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.dto.DeviceDataPageReqDto;
import com.zzyl.serve.listener.IotMsgNotifyData;
import com.zzyl.serve.listener.IotMsgService;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.service.IDeviceDataService;
import com.zzyl.serve.vo.DeviceReportDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 *
 * @author liuyp
 * @date 2025-08-23
 */
@Slf4j
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param dto 查询条件
     * @return 设备数据
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto) {
        LambdaQueryWrapper<DeviceData> wrapper = Wrappers.<DeviceData>lambdaQuery()
                .like(StringUtils.isNotEmpty(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StringUtils.isNotEmpty(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime);

        Page<DeviceData> page = page(Page.of(dto.getPageNum(), dto.getPageSize()), wrapper);

        TableDataInfo<DeviceData> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        return tableDataInfo;
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }

    @Override
    public void batchSaveDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        // 1. 先查询设备信息，如果找不到就直接结束
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId);
        Device device = deviceMapper.selectOne(wrapper);
        if (device == null) {
            log.error("物联网-找不到设备信息，iotId:{}", deviceId);
            return;
        }

        // 2. 再将上报的数据保存到表里
        List<DeviceData> list = new ArrayList<>();
        IotMsgService service = iotMsgNotifyData.getBody().getServices().get(0);
        // 2.1 取数据的上报时间
        String eventTimeStr = service.getEventTime();
        LocalDateTime dateTime = LocalDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        LocalDateTime eventTime = dateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        // 2.2 循环每个物模型的数据
        Map<String, Object> properties = service.getProperties();
        properties.forEach((prop, value) -> {
            DeviceData deviceData = new DeviceData();
            deviceData.setFunctionId(prop);
            deviceData.setDataValue(String.valueOf(value));
            deviceData.setAlarmTime(eventTime);
            deviceData.setIotId(deviceId);
            deviceData.setDeviceName(device.getDeviceName());
            deviceData.setProductKey(device.getProductKey());
            deviceData.setProductName(device.getProductName());
            deviceData.setAccessLocation(device.getBindingLocation());
            deviceData.setLocationType(device.getLocationType());
            deviceData.setPhysicalLocationType(device.getPhysicalLocationType());
            deviceData.setDeviceDescription(device.getDeviceDescription());

            list.add(deviceData);
        });

        saveBatch(list);

        //将设备上报的数据缓存到Redis里：用哈希结构存储，大key 固定值即可，小key 使用设备id， value值 此设备的所有物模型数据
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId, JSONUtil.toJsonStr(list));
    }

    @Override
    public List<DeviceReportDataVo> queryServiceProperties(String iotId) {
        //从redis中取出数据
        String deviceDataStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        List<DeviceData> list = JSONUtil.toList(deviceDataStr, DeviceData.class);
        DeviceData deviceData = list.get(1);
        List<DeviceReportDataVo> vos = new ArrayList<>();
            DeviceReportDataVo vo = new DeviceReportDataVo();
            vo.setEventTime(deviceData.getAlarmTime());
            vo.setValue(deviceData.getDataValue());
            vo.setFunctionId(deviceData.getFunctionId());
            vos.add(vo);

        return vos;
    }
}
